package org.eclipse.equinox.spring.osgi;
/**
 * This file is part of org.springframework.equinox.deployer. 
 * Copyright (C) olivier.evalet@genebio.com and genebio team
 * 
 * org.springframework.equinox.deployer is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 * 
 * org.springframework.equinox.deployer is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * org.springframework.equinox.deployer. If not, see <http://www.gnu.org/licenses/>.
 * 
 */

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.osgi.framework.BundleContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;

public class OsgiContextLoaderListener implements ServletContextListener {

	private OsgiContextLoader contextLoader;
	private BundleContext bundleContext;
	private ApplicationContext appContext;


	public OsgiContextLoaderListener(ApplicationContext appContext, BundleContext bundleContext) {
		this.bundleContext=bundleContext;
		this.appContext=appContext;
	}

	/**
	 * Initialize the root web application context.
	 */
	public void contextInitialized(ServletContextEvent event) {
		this.contextLoader = createContextLoader();
		this.contextLoader.initWebApplicationContext(event.getServletContext(), bundleContext);
	}

	/**
	 * Create the ContextLoader to use. Can be overridden in subclasses.
	 * @return the new ContextLoader
	 */
	protected OsgiContextLoader createContextLoader() {
		return new OsgiContextLoader(appContext);
	}

	/**
	 * Return the ContextLoader used by this listener.
	 * @return the current ContextLoader
	 */
	public ContextLoader getContextLoader() {
		return this.contextLoader;
	}


	/**
	 * Close the root web application context.
	 */
	public void contextDestroyed(ServletContextEvent event) {
		if (this.contextLoader != null) {
			this.contextLoader.closeWebApplicationContext(event.getServletContext());
		}
	}

}
